#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>

#define PORT 8080
#define BUFFER_SIZE 1024

int main() {
    int server_fd, new_socket;
    struct sockaddr_in address;
    int addrlen = sizeof(address);
    char buffer[BUFFER_SIZE] = {0};
    int sum = 0;

    // 创建socket文件描述符
    if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
        perror("socket failed");
        exit(EXIT_FAILURE);
    }

    // 绑定socket到端口
    address.sin_family = AF_INET;
    address.sin_addr.s_addr = INADDR_ANY;
    address.sin_port = htons(PORT);

    if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
        perror("bind failed");
        exit(EXIT_FAILURE);
    }

    // 开始监听
    if (listen(server_fd, 3) < 0) {
        perror("listen");
        exit(EXIT_FAILURE);
    }

    printf("Server is listening on port %d...\n", PORT);

    // 接受连接
    if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t *)&addrlen)) < 0) {
        perror("accept");
        exit(EXIT_FAILURE);
    }

    printf("Connection established with client.\n");

    // 接收数据
    while (1) {
        int n = read(new_socket, buffer, BUFFER_SIZE);
        if (n <= 0) {
            break;
        }

        // 将接收到的数据转换为整数并累加
        int num = atoi(buffer);
        if (num == 0) {
            break;
        }
        sum += num;

        // 清空缓冲区
        memset(buffer, 0, BUFFER_SIZE);
    }

    printf("The sum is: %d\n", sum);

    // 将结果发送回客户端
    char result[10];
    snprintf(result, sizeof(result), "%d", sum);
    send(new_socket, result, strlen(result), 0);

    // 关闭socket
    close(new_socket);
    close(server_fd);

    return 0;
}